<template>
  <el-row type="flex" justify="center" :gutter="12">
    <el-col :span="7">
      <ProjectList
        @updateCurrProject="handleCurrentRowChange"
        pagination-layout="total, sizes, prev, pager, next"
        :reload="isRefreshProjectList"
        show-operator
        ref="projectList"
      ></ProjectList>
    </el-col>
    <el-col :span="15">
      <el-collapse :value="currentProjectData ? 'info' : ''" v-loading="collapseLoading" @change="collChange" accordion>
        <el-collapse-item :disabled="!currentProjectData" name="info">
          <el-tag size="medium" slot="title">
                <span>
                  项目基础信息
                  <span v-if="!currentProjectData">
                    （
                    <span style="color: #F56C6C">未选择项目</span>
                    ）
                  </span>
                </span>
          </el-tag>
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <el-dropdown type="primary" split-button v-if="currentProjectData && isCurrentProjectCreator" size="medium">
                <span>项目操作</span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button :disabled="!currentProjectData" size="small" type="info" icon="el-icon-refresh" title="刷新数据" @click="refreshData()">刷新</el-button>
                  </el-dropdown-item>
                  <div class="menu-divider"></div>
                  <el-dropdown-item>
                    <el-popover trigger="click" v-model="visible">
                      <el-button slot="reference" :disabled="!currentProjectData" size="small" type="primary" icon="el-icon-edit-outline" title="修改项目信息">修改</el-button>
                      <ProjectForm :project-data="currentProject" ref="updateProjectForm" @closeForm="handleCloseForm" form-type="update"></ProjectForm>
                    </el-popover>
                  </el-dropdown-item>
                  <div class="menu-divider"></div>
                  <el-dropdown-item v-if="currentProjectData.state !== 'PROCESSING'">
                    <el-button :disabled="!currentProjectData" size="small" type="primary" icon="el-icon-check" @click="updateProjectState('00', currentProjectData.id)" title="继续项目">恢复</el-button>
                  </el-dropdown-item>
                  <div class="menu-divider"></div>
                  <el-dropdown-item v-if="currentProjectData.state !== 'PAUSED'">
                    <el-button :disabled="!currentProjectData" size="small" type="warning" icon="el-icon-check" @click="updateProjectState('10', currentProjectData.id)" title="暂停项目">暂停</el-button>
                  </el-dropdown-item>
                  <div class="menu-divider"></div>
                  <el-dropdown-item v-if="currentProjectData.state !== 'COMPLETED'">
                    <el-button :disabled="!currentProjectData" size="small" type="success" icon="el-icon-check" @click="updateProjectState('20', currentProjectData.id)" title="标记完成">结项</el-button>
                  </el-dropdown-item>
                  <div class="menu-divider"></div>
                  <el-dropdown-item>
                    <el-popconfirm title="确认删除？" @onConfirm="deleteCurrentProject(currentProjectData.id)">
                      <el-button :disabled="!currentProjectData" slot="reference" size="small" type="danger" icon="el-icon-delete" title="删除项目">删除</el-button>
                    </el-popconfirm>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button v-else :disabled="!currentProjectData" size="small" type="info" icon="el-icon-refresh" title="刷新数据" @click="refreshData()">刷新</el-button>
            </div>
            <transition name="el-zoom-in-center">
              <ProjectInfo v-if="currentProjectData" :project="currentProjectData"></ProjectInfo>
            </transition>
          </el-card>
        </el-collapse-item>
        <el-collapse-item :disabled="!currentProjectData" name="member">
          <el-tag size="medium" slot="title">
            <span>项目成员列表（<span style="color: #343937">{{ memberCount > 0 ? '共' + memberCount + '个成员' : '选择项目以查看' }}</span>）</span>
          </el-tag>
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <el-button-group>
                <el-popover>
                  <el-button slot="reference" title="邀请其他用户加入" type="success">邀请</el-button>
                  <el-input v-model="inviteUserId" placeholder="请输入用户邮箱或ID"></el-input>
                  <el-button size="medium" style="width: 100%; margin-top: 10px" type="primary" @click="inviteUser">邀请</el-button>
                </el-popover>
                <el-popconfirm title="确认退出该项目？" @onConfirm="exitProject" v-if="!isCurrentProjectCreator">
                  <el-button slot="reference" title="退出当前项目" type="danger">退出</el-button>
                  <div>exit project</div>
                </el-popconfirm>
              </el-button-group>
            </div>
            <ProjectMemberList @memberCount="handleMembersCountUpdate" :project-id="currentProjectData.id" v-if="currentProjectData" v-show="projectMemberListRender"></ProjectMemberList>
          </el-card>
        </el-collapse-item>
        <el-collapse-item name="timeline">
          <el-tag size="medium" slot="title">
            <span>重要任务节点时间线（<span style="color: #343937">{{ timeLineCount > 0 ? '共' + timeLineCount + '个重大节点' : '暂无数据' }}</span>）</span>
          </el-tag>
          <transition name="el-zoom-in-top">
            <el-card shadow="hover" v-if="currentProjectTodos && timeLineCount > 0">
              <div slot="header" class="clearfix">
                <el-button :loading="timelineLoading" @click="refreshTimeline" icon="el-icon-refresh" title="刷新" circle></el-button>
              </div>
              <ProjectTimeLine ref="timeline" @timelineCounts="handleTimelineCountUpdate" :project-id="currentProjectData.id"></ProjectTimeLine>
            </el-card>
            <el-card v-else>
              <el-tag type="info">暂无数据</el-tag>
            </el-card>
          </transition>
        </el-collapse-item>
      </el-collapse>
    </el-col>
  </el-row>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import ProjectList from '@/components/ProjectList'
import ProjectInfo from '@/components/ProjectInfo'
import ProjectMemberList from '@/components/ProjectMemberList'
import ProjectTimeLine from '@/components/ProjectTimeLine'
import ProjectForm from '@/components/ProjectForm'
import {exitProject, getProjectData, sendInvitation, updateProject} from '@/api/project'
import {getTodos} from '@/api/todo'

export default {
  name: 'Project',
  inject: ['reload'],
  components: {
    Header,
    Footer,
    ProjectList,
    ProjectInfo,
    ProjectMemberList,
    ProjectTimeLine,
    ProjectForm
  },
  data () {
    return {
      count: 8,
      currentProject: undefined,
      currentPage: 1,
      pageSize: 10,
      projectLogos: undefined,
      render: {
        timeline: true,
        projectMemberList: true
      },
      timeLineCount: 0,
      memberCount: 0,
      currentProjectInfo: undefined,
      visible: false,
      refreshProjectList: false,
      collapseLoading: false,
      projectData: undefined,
      inviteUserId: undefined,
      inviteVisible: false,
      timelineLoading: false
    }
  },
  methods: {
    handleCurrentRowChange (rowId, rowName, desc) {
      this.collapseLoading = true
      setTimeout(() => {
        this.currentProject = {
          id: rowId + '',
          name: rowName,
          description: desc
        }
        this.loadProjectInformation(this.currentProject.id)
        this.loadProjectTodo(rowId)
        this.collapseLoading = false
      }, 300)
    },
    loadProjectTodo (id) {
      getTodos(id, undefined, false, 0, 1000).then(res => {
        this.$store.commit('SET_CURRENT_PROJECT_TODOS', res.data)
        this.timeLineCount = res.data.length
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
    },
    handleCurrentChange (val) {
      this.currentPage = val
    },
    rowSelect (row, col, event) {
      this.currentProject = row
    },
    deleteCurrentProject (id) {
      let formData = {
        enable: '20'
      }
      updateProject(formData, id).then(() => {
        this.$notify.success('删除成功')
      }).catch(res => {
        this.$notify.error({
          title: '删除失败',
          message: res.msg
        })
      })
      this.currentProject = undefined
      this.$store.dispatch('SetCurrentProject', undefined)
      this.refreshProjectList = !this.refreshProjectList
    },
    updateProjectState (state, id) {
      let formData = {
        state: state
      }
      updateProject(formData, id).then(() => {
        this.loadProjectInformation(id)
        this.$notify.success('更新成功')
      }).catch(res => {
        this.$notify.error({
          title: '更新失败',
          message: res.msg
        })
      })
      this.refreshData()
    },
    handleTimelineCountUpdate (count) {
      this.timeLineCount = count
    },
    refreshData (delay = 300) {
      this.collapseLoading = true
      setTimeout(() => {
        this.$set(this.currentProject, 'id', this.$store.getters.currentProject)
        this.loadProjectInformation(this.currentProject.id)
        this.collapseLoading = false
      }, delay)
    },
    handleMembersCountUpdate (count) {
      this.memberCount = count
    },
    handleProjectDataLoad (data) {
      this.currentProjectInfo = data
    },
    handleCloseForm (state = false) {
      this.visible = state
      new Promise(resolve => {
        this.refreshData()
        resolve()
      }).then(() => {
        this.$refs.projectList.refreshTable()
        // 延后一秒再刷新表单数据
        setTimeout(() => {
          this.$refs.updateProjectForm.init()
        }, 1000)
      })
    },
    exitProject () {
      let projectId = this.$store.getters.currentProject
      let userId = this.$store.getters.currentUserId
      exitProject(projectId, userId).then(() => {
        this.$notify.success('退出成功，即将刷新页面')
        this.$store.dispatch('ClearCache')
        this.resetData()
        this.refreshProjectList = !this.refreshProjectList
      }).catch(error => {
        this.$notify.error({
          title: '退出失败',
          message: error.message
        })
      })
    },
    resetData () {
      this.currentProject = undefined
      this.currentProjectInfo = undefined
    },
    loadProjectInformation (id) {
      getProjectData(id).then(res => {
        let data = res.data
        this.projectData = [
          {
            name: 'ID',
            value: data.id
          },
          {
            name: '名称',
            value: data.name
          },
          {
            name: '描述',
            value: data.description
          },
          {
            name: '进度',
            value: data.state
          },
          {
            name: '创建者',
            value: data.creatorId
          },
          {
            name: '创建时间',
            value: data.createTime
          }
        ]
        this.$store.commit('SET_CURRENT_PROJECT_DATA', res.data)
        this.$store.dispatch('SetCurrentProjectCreator', data.creatorId)
      }).catch(res => {
        this.$notify.error({
          title: '加载项目信息失败',
          message: res.msg
        })
      })
    },
    inviteUser () {
      if (!this.inviteUserId) {
        this.$notify.warning('目标用户不存在')
      } else {
        sendInvitation(this.currentProject.id, this.inviteUserId).then(() => {
          this.$notify.success({
            title: '邀请已发送',
            message: '邀请已发送给用户 ' + this.inviteUserId
          })
        }).catch(error => {
          this.$notify.error(error)
        }).finally(() => {
          this.inviteVisible = !this.inviteVisible
          this.inviteUserId = undefined
        })
      }
    },
    refreshTimeline () {
      this.timelineLoading = true
      setTimeout(() => {
        this.$refs.timeline.init()
        this.timelineLoading = false
      }, 300)
    },
    collChange (val) {
      console.log(val)
    }
  },
  computed: {
    timelineRender () {
      return this.render.timeline
    },
    currentProjectData () {
      return this.$store.getters.currentProjectData
    },
    projectMemberListRender () {
      return this.render.projectMemberList
    },
    isRefreshProjectList () {
      return this.refreshProjectList
    },
    isCurrentProjectCreator () {
      if (!this.$store.getters.currentProjectCreator) {
        return false
      }
      return this.$store.getters.currentProjectCreator === this.$store.getters.currentUserId
    },
    currentProjectTodos () {
      return this.$store.getters.currentProjectTodos
    }
  },
  created () {
    this.$store.dispatch('SetCurrentMenu', '项目')
  }
}
</script>

<style lang="scss" scoped>
.el-main {
  min-height: calc(100vh - 149px);
  margin-top: 30px;
}
.text-item {
  margin-bottom: 18px;
}
.el-card {
  border: 1px solid #d9dce2;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.float-right {
  float: right;
}
.dropdown-item-margin {
  margin-top: 18px;
}
.menu-divider {
  margin: 8px 0;
  width: 100%;
}
</style>
